package ohc.login

import com.google.gson.Gson
import com.google.gson.JsonObject
import java.net.URI
import java.net.URLEncoder
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.nio.charset.StandardCharsets
import java.time.Duration
import java.util.concurrent.CompletableFuture

/**
 * API 服务类，用于与远程服务器通信
 */
object ApiService {
    private val httpClient: HttpClient = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(10))
        .build()
    private val gson = Gson()
    
    /**
     * 登录结果数据类
     */
    data class LoginResult(
        val success: Boolean,
        val uid: Long? = null,
        val token: String? = null,
        val avatarUrl: String? = null,
        val coverUrl: String? = null,
        val ifTodayFirstLogin: Boolean? = null,
        val errorCode: String? = null
    )
    
    /**
     * 异步登录请求
     * @param uidEmail 用户 UID 或邮箱
     * @param password 密码
     * @return 登录结果的 CompletableFuture
     */
    fun loginAsync(uidEmail: String, password: String): CompletableFuture<LoginResult> {
        return CompletableFuture.supplyAsync {
            try {
                val encodedUidEmail = URLEncoder.encode(uidEmail, StandardCharsets.UTF_8)
                val encodedPassword = URLEncoder.encode(password, StandardCharsets.UTF_8)
                val url = "${Config.apiBaseUrl}/?module=auth&action=login&uid_email=$encodedUidEmail&pw=$encodedPassword"
                
                Ohc_login.logger.info("正在请求 API: ${Config.apiBaseUrl}/?module=auth&action=login&uid_email=$encodedUidEmail&pw=***")
                
                val request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .GET()
                    .timeout(Duration.ofSeconds(10))
                    .build()
                
                val response = httpClient.send(request, HttpResponse.BodyHandlers.ofString())
                val responseBody = response.body()
                
                Ohc_login.logger.info("API 响应: $responseBody")
                
                val json = gson.fromJson(responseBody, JsonObject::class.java)
                
                // 检查是否有错误状态
                if (json.has("status") && json.get("status").asString == "error") {
                    val errorCode = json.get("message")?.asString ?: "system_error"
                    return@supplyAsync LoginResult(success = false, errorCode = errorCode)
                }
                
                // 检查旧格式的错误码
                if (json.has("error")) {
                    val errorCode = json.get("error").asString
                    return@supplyAsync LoginResult(success = false, errorCode = errorCode)
                }
                
                // 检查是否有必要的成功字段
                if (!json.has("uid") || !json.has("token")) {
                    Ohc_login.logger.error("API 响应缺少必要字段: $responseBody")
                    return@supplyAsync LoginResult(success = false, errorCode = "system_error")
                }
                
                // 解析成功响应
                LoginResult(
                    success = true,
                    uid = json.get("uid")?.asLong,
                    token = json.get("token")?.asString,
                    avatarUrl = json.get("avatar_url")?.asString,
                    coverUrl = json.get("cover_url")?.asString,
                    ifTodayFirstLogin = json.get("if_today_first_login")?.asBoolean
                )
            } catch (e: Exception) {
                Ohc_login.logger.error("API 登录请求失败: ${e.message}")
                e.printStackTrace()
                LoginResult(success = false, errorCode = "system_error")
            }
        }
    }
    
    /**
     * 用户详情结果数据类
     */
    data class UserDetailResult(
        val success: Boolean,
        val uid: Long? = null,
        val username: String? = null,
        val intro: String? = null,
        val time: String? = null,
        val sex: String? = null,
        val honour: String? = null,
        val experience: Int? = null,
        val avatarUrl: String? = null,
        val coverUrl: String? = null,
        val videoNum: Int? = null,
        val blogNum: Int? = null,
        val followingsCount: Int? = null,
        val fansCount: Int? = null,
        val errorCode: String? = null
    )
    
    /**
     * 异步获取用户详情
     * @param uid 用户 UID
     * @return 用户详情结果的 CompletableFuture
     */
    fun getUserDetailAsync(uid: Long): CompletableFuture<UserDetailResult> {
        return CompletableFuture.supplyAsync {
            try {
                val url = "${Config.apiBaseUrl}/?module=user&action=get_user_detail&uid=$uid"
                
                Ohc_login.logger.info("正在请求用户详情 API: $url")
                
                val request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .GET()
                    .timeout(Duration.ofSeconds(10))
                    .build()
                
                val response = httpClient.send(request, HttpResponse.BodyHandlers.ofString())
                val responseBody = response.body()
                
                Ohc_login.logger.info("用户详情 API 响应: $responseBody")
                
                val json = gson.fromJson(responseBody, JsonObject::class.java)
                
                // 检查是否有错误状态
                if (json.has("status") && json.get("status").asString == "error") {
                    val errorCode = json.get("message")?.asString ?: "system_error"
                    return@supplyAsync UserDetailResult(success = false, errorCode = errorCode)
                }
                
                // 检查旧格式的错误码
                if (json.has("error")) {
                    val errorCode = json.get("error").asString
                    return@supplyAsync UserDetailResult(success = false, errorCode = errorCode)
                }
                
                // 检查是否有必要的成功字段
                if (!json.has("uid") || !json.has("username")) {
                    Ohc_login.logger.error("用户详情 API 响应缺少必要字段: $responseBody")
                    return@supplyAsync UserDetailResult(success = false, errorCode = "system_error")
                }
                
                // 解析成功响应
                UserDetailResult(
                    success = true,
                    uid = json.get("uid")?.asLong,
                    username = json.get("username")?.asString,
                    intro = json.get("intro")?.asString,
                    time = json.get("time")?.asString,
                    sex = json.get("sex")?.asString,
                    honour = json.get("honour")?.asString,
                    experience = json.get("experience")?.asInt,
                    avatarUrl = json.get("avatar_url")?.asString,
                    coverUrl = json.get("cover_url")?.asString,
                    videoNum = json.get("video_num")?.asInt,
                    blogNum = json.get("blog_num")?.asInt,
                    followingsCount = json.get("followings_count")?.asInt,
                    fansCount = json.get("fans_count")?.asInt
                )
            } catch (e: Exception) {
                Ohc_login.logger.error("获取用户详情请求失败: ${e.message}")
                e.printStackTrace()
                UserDetailResult(success = false, errorCode = "system_error")
            }
        }
    }
    
    /**
     * 将错误码转换为中文提示
     */
    fun getErrorMessage(errorCode: String): String {
        return when (errorCode) {
            "missing_argument" -> "缺少参数"
            "error_password" -> "密码错误"
            "error_module" -> "API 模块错误，请检查接口路径"
            "system_error" -> "系统错误，请稍后重试"
            "too_many_requests" -> "请求过于频繁，请稍后重试"
            else -> "未知错误: $errorCode"
        }
    }
    
    /**
     * 检查 API 是否可用
     */
    fun checkApiAvailableAsync(): CompletableFuture<Boolean> {
        return CompletableFuture.supplyAsync {
            try {
                // 检测 API 连通性
                val url = "${Config.apiBaseUrl}/?module=user&action=get_user_detail&uid=1"
                
                val request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .GET()
                    .timeout(Duration.ofSeconds(5))
                    .build()
                
                val response = httpClient.send(request, HttpResponse.BodyHandlers.ofString())
                // 只要能收到响应就认为 API 可用
                response.statusCode() in 200..499
            } catch (e: Exception) {
                Ohc_login.logger.warn("API 连接检测失败: ${e.message}")
                false
            }
        }
    }
}
